﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.ComponentModel;
using System.ServiceModel.DomainServices.Client;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections;
namespace Infrastructure.Silverlight.Converts
{

    public class ObservableEntityList<T> : ObservableCollection<T> 
        where  T: System.ServiceModel.DomainServices.Client.Entity
    {

        public ObservableEntityList(EntitySet<T> input)
            : base(input)
        {
            this._EntitySet = input;
        }
        public EntitySet<T> _EntitySet { get; set; }
        protected override void InsertItem(int index, T item)
        {
            _EntitySet.Add(item);
            base.InsertItem(index, item);
        }
        
        protected override void RemoveItem(int index)
        {
            if (this.Items.ElementAt(index) != null)
                this._EntitySet.Remove(this.Items.ElementAt(index));
            base.RemoveItem(index);
        }
    }

    public class EntityListDataFormConverter : IValueConverter
    {


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ( value != null)
                return this.FromEntityList(value as EntitySet);
            return null;
             
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        public IEnumerable FromEntityList(EntitySet entityList)
        {
            Type listType = entityList.GetType();
            Type[] genericArgs = listType.GetGenericArguments();
            if (genericArgs.Length != 1)
            {
                 throw new ArgumentException("entityList must be an EntityList<T>");
            }
            Type collectionViewType = typeof(ObservableEntityList<>).MakeGenericType(genericArgs.Single());
            return Activator.CreateInstance(collectionViewType, entityList) as IEnumerable;
        }
    }
}
